package com.fingard.dsp.bank.directbank.fc11;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import com.fingard.constant.DateFormat2;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.directConfig.FtpSet;
import com.fingard.dsp.bank.directConfig.TaskTimerSet;
import com.fingard.dsp.bank.directbank.bankInterface.IScheduleTask;
import com.fingard.io.FileHelper;
import com.fingard.net.ConnState;
import com.fingard.net.FtpReceiver;
import com.fingard.net.SftpPortClient;
import com.fingard.text.StringHelper;

/**
 * 富聪定时任务
 * 
 * 需求：每小时轮询富聪SFTP服务器是否存在上传文件，不存在则本地创建空文件上传
 * @author fanghh
 * @date 2018/7/26
 */
public class FC11ScheduleTask extends FC11Base implements IScheduleTask {
	@Override
	public void execTask(TaskTimerSet timerSet) {
		 try {
	            if (timerSet.taskNameList.toLowerCase().contains("automakefile")) {
	                autoMakeFile();
	            }
	        } catch (Exception ex) {
	        	ex.printStackTrace();
	            this.WriteBankLogLn(ex);
	        }
	}
	
	public void autoMakeFile(){
		SftpPortClient sftpPortClient = null;
		
    	try{
    		Date tmpDateNow = new Date();
    		Calendar tmpNewDateNow = Calendar.getInstance();
			tmpNewDateNow.setTime(tmpDateNow);
			String tmpMinutesNow = getBankConfig().getValueAsString("taskTimeMinutes");
			if (tmpNewDateNow.get(Calendar.MINUTE) < Integer.parseInt(tmpMinutesNow)) {
				System.out.println("FC11未到执行分钟数");
				return;
			}
			
			String nowDateHour = new SimpleDateFormat("yyyyMMddHH").format(tmpDateNow);
			if(bankFront.customMap.containsKey("lastUpFileDateHour")){
				if(nowDateHour.equals(bankFront.customMap.get("lastUpFileDateHour"))){
					System.out.println("FC11当前小时不需再产生空文件");
					return;
				}
			}
    		
    		FtpSet ftpSet = bankFront.getFtpSet("refund_upload");
			sftpPortClient = new SftpPortClient(ftpSet);
			String  directDir = "";
			
			String tmpDate = Format.Date8Format.format(tmpDateNow);
			if (ftpSet.upDir.endsWith("/")) {
				directDir = tmpDate;
			} else {
				directDir = "/" + tmpDate;
			}
			
			String refundFileName = bankFront.org + "_transfer_" + new DateFormat2("yyyyMMddHHmm").format(tmpDateNow);
			
			WriteBankLogLn2("开始遍历服务器目录:" + ftpSet.upDir + directDir);
			//boolean isContinue = false;
			FtpReceiver ftpListFileReceiver = sftpPortClient.listFiles(ftpSet.upDir + directDir);
			if (!ftpListFileReceiver.isCompleted) {
				if (ConnState.FILE_NOT_EXISTS.equals(ftpListFileReceiver.connState) || ftpListFileReceiver.connMsg.contains("不存在")) {
					//Calendar tmpNewDate = Calendar.getInstance();
					//tmpNewDate.setTime(tmpDateNow);
					//String tmpMinutes = getBankConfig().getValueAsString("taskTimeMinutes");
					//if (tmpNewDate.get(Calendar.MINUTE) < Integer.parseInt(tmpMinutes)) {
						//sftpPortClient.disconnect();
					//	return;
					//}// else {
					//	isContinue = true;
					//}
					WriteBankLogLn2("FILE_NOT_EXISTS");
				} else {
					WriteBankLogLn2("遍历目录:" + ftpSet.downDir + directDir + "失败!");
					//sftpPortClient.disconnect();
					return;
				}
			} else {
				WriteBankLogLn2("sftp服务器目录文件列表:\r\n" + ftpListFileReceiver.connMsg);
				List<String> fileNameList = Arrays.asList(ftpListFileReceiver.connMsg.split(","));
				Iterator<String> it = fileNameList.iterator();
				String localRefundFileName = refundFileName + ".txt";
				
				while (it.hasNext()) {
					String sftpFileName = ((String)it.next()).toString();
					if (sftpFileName.length() <= 0) {
						continue;
					}
						
					int timeIndex = sftpFileName.lastIndexOf("_");
					if(timeIndex<0){
						continue;
					}
					timeIndex = timeIndex+1;
					String sftpFileDateTime = sftpFileName.substring(timeIndex,timeIndex+12);
					String localRefundFileDateTime = localRefundFileName.substring(timeIndex,timeIndex+12);
					
					// 如果当前服务器目录已经存在同小时的文件且分钟不在指定分钟内，不执行定时任务
					if (sftpFileDateTime.substring(0, 10).equals(localRefundFileDateTime.substring(0, 10))) {
						//sftpPortClient.disconnect();
						//记录上次小时
						bankFront.customMap.put("lastUpFileDateHour", sftpFileDateTime.substring(0, 10));
						return;
					}
				}
			}
			
			//if (isContinue) {
				// 生成待上传文件并写入内容
				String refundFileDir = getRefundFileDirectory();
				String localRefundFilePath = refundFileDir + File.separator + refundFileName + ".txt";
				WriteBankLogLn2("本地模拟退保文件路径: " + localRefundFilePath);
				FileHelper.writeFile(localRefundFilePath, "version:1|总笔数:0\r\n", getCharset());
				
				String sftpFilePath = StringHelper.trimEnd(ftpSet.upDir, "/") + "/" + tmpDate + "/" + refundFileName + ".txt";
				WriteBankLogLn2("SFTP服务器空文件上传路径:" + sftpFilePath);
				
				FtpReceiver ftpReceiver = sftpPortClient.uploadFile(directDir, localRefundFilePath, sftpFilePath);

				if (ftpReceiver.isCompleted) {
					WriteBankLogLn2("文件上传成功");
					bankFront.customMap.put("lastUpFileDateHour", nowDateHour);
				} else if (ConnState.FAIL.equals(ftpReceiver.connState)) {
					WriteBankLogLn2("文件上传通讯失败");
				} else {
					WriteBankLogLn2(ftpReceiver.connMsg);
				}
			//}
    	}catch(Exception ex){
    		ex.printStackTrace();
    		WriteBankLogLn(ex);
    	}finally{
    		if(sftpPortClient != null){
    			try {
					sftpPortClient.disconnect();
				} catch (IOException e) {
					e.printStackTrace();
					WriteBankLogLn(e);
				}
    		}
    	}
    }
}
